package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fsdfs.FastDFSClientUtil;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Value("${fileServerUrl}")
    private String imageUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile file) {

        try {
            //1:校验文件完整性
            if (file == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            //2:完成上传得到fullpath
            String path = fastDFSClientUtil.uploadFile(file);

            //3:insert wmmaterial 表
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(path);
            wmMaterial.setIsCollection((short)0);

            WmUser wmUser = WmThreadLocalUtils.getUser();
            if(wmUser!=null){
                wmMaterial.setUserId(wmUser.getId()); //获取当前登录用户id
            }
            wmMaterial.setType((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();


        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper =new LambdaQueryWrapper<>();

        WmUser user = WmThreadLocalUtils.getUser();
        if(user!=null){
            lambdaQueryWrapper.eq(WmMaterial::getUserId,user.getId());
        }
        if(dto.getIsCollection()!=null){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page page =new Page(dto.getPage(),dto.getSize());
        IPage result =page(page,lambdaQueryWrapper);

        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());

        List<WmMaterial> wmMaterialList = result.getRecords();

        List<WmMaterial> list = wmMaterialList.stream().map(a -> {
            a.setUrl(imageUrl.concat(a.getUrl()));
            return a;
        }).collect(Collectors.toList());

//        for(WmMaterial w :wmMaterialList){
//            w.setUrl(imageUrl.concat(w.getUrl()));
//        }

        responseResult.setData(list);

        return responseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {

        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据素材id查询是否被引用
        QueryWrapper<WmNewsMaterial> queryWrapper =new QueryWrapper<>();
        queryWrapper.lambda().eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(queryWrapper);
        if(count>0){
            //有引用
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //删除fastdfs图片
        fastDFSClientUtil.delFile(wmMaterial.getUrl());

        //删除 素材表信息
        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
